/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package megamar;

import com.toedter.calendar.IDateEditor;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.JTextComponent;

/**
 *
 * @author pedro.lizondo
 */
public class Pagos extends javax.swing.JDialog {

    private String idzona;
    //private int num_creditos;
    private int id_cliente;
    private float valor_cuota;
    private float compra_total;
    public static final SimpleDateFormat FORMATO_YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd"); //Here put your format
    private boolean clientevalido;
    private String idusuario;

    /**
     * Creates new form Pagos
     */
    public Pagos(String idz, String nomzona, String idus, java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        jdfechapago.setLocale(Locale.getDefault());  //Define el idioma del calendar
        IDateEditor editorDC = (IDateEditor) jdfechapago.getDateEditor();
        editorDC.getUiComponent().addKeyListener(new KeyListener() {

            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == e.VK_ENTER) {
                    // put the code you want to execute when Enter is pressed here 
                    //System.out.println("ENTER PRESSED");
                    txtpago.requestFocusInWindow();
                }
            }

            public void keyReleased(KeyEvent keyEvent) {
                //printIt("Released", keyEvent);
            }

            public void keyTyped(KeyEvent keyEvent) {
                //printIt("Typed", keyEvent);
            }

            /*            private void printIt(String title, KeyEvent keyEvent) {
            int keyCode = keyEvent.getKeyCode();
            String keyText = KeyEvent.getKeyText(keyCode);
            System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar());
            }
             * 
             */
        });
        idzona = idz;
        //labelzona.setText(nomzona);
        this.setLocationRelativeTo(null);
        txtcodigocliente.requestFocus();
        jpanelpago.setVisible(false);
        idusuario = idus;
    }

    public boolean getclientevalido() {
        return clientevalido;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel4 = new javax.swing.JPanel();
        jLabel15 = new javax.swing.JLabel();
        txtcodigocliente = new javax.swing.JTextField();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jbvercreditos = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jLabel16 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        jPanel7 = new javax.swing.JPanel();
        txtdni = new javax.swing.JTextField();
        txtnombre = new javax.swing.JTextField();
        txtdomicilioparticular = new javax.swing.JTextField();
        txtbarrioparticular = new javax.swing.JTextField();
        jPanel8 = new javax.swing.JPanel();
        jLabel14 = new javax.swing.JLabel();
        jLabel23 = new javax.swing.JLabel();
        jLabel24 = new javax.swing.JLabel();
        jLabel25 = new javax.swing.JLabel();
        jPanel9 = new javax.swing.JPanel();
        txtdomiciliocomercial = new javax.swing.JTextField();
        txtbarriocomercial = new javax.swing.JTextField();
        txttelefono = new javax.swing.JTextField();
        txtrubro = new javax.swing.JTextField();
        jpanelpago = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtpago = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtincremento = new javax.swing.JTextField();
        jdfechapago = new com.toedter.calendar.JDateChooser("dd/MM/yyyy", "##/##/##", '_');
        jButtonAceptar = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        txtcompra = new javax.swing.JTextField();
        txtpagado = new javax.swing.JTextField();
        txtatrasototal = new javax.swing.JTextField();
        txtsaldo = new javax.swing.JTextField();
        txtincrementototal = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablacreditos = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jButtonEliminarCredito1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Pagos");

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Buscar Cliente"));

        jLabel15.setText("Codigo");

        txtcodigocliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtcodigoclienteKeyPressed(evt);
            }
        });

        jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Sherlocks_Tool.png"))); // NOI18N
        jButton7.setText("Buscar");
        jButton7.setPreferredSize(new java.awt.Dimension(111, 41));
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/clientes_32.png"))); // NOI18N
        jButton8.setText("Ver Listado de Clientes");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        jbvercreditos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/clientes_32.png"))); // NOI18N
        jbvercreditos.setText("Seleccionar Credito");
        jbvercreditos.setEnabled(false);
        jbvercreditos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbvercreditosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel15)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtcodigocliente, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jbvercreditos)
                .addContainerGap(189, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(txtcodigocliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton8)
                    .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbvercreditos))
                .addContainerGap())
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Cliente"));

        jPanel6.setLayout(new java.awt.GridLayout(4, 0, 5, 5));

        jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel16.setText("DNI");
        jPanel6.add(jLabel16);

        jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel9.setText("Apellido y Nombre");
        jPanel6.add(jLabel9);

        jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel17.setText("Domicilio Particular");
        jPanel6.add(jLabel17);

        jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel20.setText("Barrio Particular");
        jPanel6.add(jLabel20);

        jPanel7.setLayout(new java.awt.GridLayout(4, 0, 5, 5));

        txtdni.setEditable(false);
        jPanel7.add(txtdni);

        txtnombre.setEditable(false);
        jPanel7.add(txtnombre);

        txtdomicilioparticular.setEditable(false);
        jPanel7.add(txtdomicilioparticular);

        txtbarrioparticular.setEditable(false);
        jPanel7.add(txtbarrioparticular);

        jPanel8.setLayout(new java.awt.GridLayout(4, 0, 5, 5));

        jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel14.setText("Domicilio Comercial");
        jPanel8.add(jLabel14);

        jLabel23.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel23.setText("Barrio Comercial");
        jPanel8.add(jLabel23);

        jLabel24.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel24.setText("Teléfono");
        jPanel8.add(jLabel24);

        jLabel25.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel25.setText("Rubro");
        jPanel8.add(jLabel25);

        jPanel9.setLayout(new java.awt.GridLayout(4, 0, 5, 5));

        txtdomiciliocomercial.setEditable(false);
        jPanel9.add(txtdomiciliocomercial);

        txtbarriocomercial.setEditable(false);
        jPanel9.add(txtbarriocomercial);

        txttelefono.setEditable(false);
        jPanel9.add(txttelefono);

        txtrubro.setEditable(false);
        jPanel9.add(txtrubro);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(54, 54, 54)
                .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(82, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel8, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
                    .addComponent(jPanel7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE))
                .addContainerGap())
        );

        jpanelpago.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Pago"));

        jLabel2.setText("Fecha del Pago");

        jLabel3.setText("Pago ($)");

        txtpago.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtpagoKeyPressed(evt);
            }
        });

        jLabel6.setText("Incremento ($)");

        txtincremento.setText("0");
        txtincremento.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtincrementoKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jpanelpagoLayout = new javax.swing.GroupLayout(jpanelpago);
        jpanelpago.setLayout(jpanelpagoLayout);
        jpanelpagoLayout.setHorizontalGroup(
            jpanelpagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpanelpagoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpanelpagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpanelpagoLayout.createSequentialGroup()
                        .addComponent(jdfechapago, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(jpanelpagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtpago, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(jpanelpagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtincremento, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jLabel2))
                .addContainerGap(496, Short.MAX_VALUE))
        );
        jpanelpagoLayout.setVerticalGroup(
            jpanelpagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpanelpagoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jpanelpagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpanelpagoLayout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpanelpagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtincremento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtpago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jpanelpagoLayout.createSequentialGroup()
                        .addGroup(jpanelpagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jdfechapago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        jButtonAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Ok.png"))); // NOI18N
        jButtonAceptar.setText("Aceptar");
        jButtonAceptar.setPreferredSize(new java.awt.Dimension(111, 41));
        jButtonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAceptarActionPerformed(evt);
            }
        });
        jButtonAceptar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jButtonAceptarKeyPressed(evt);
            }
        });

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Cancel.png"))); // NOI18N
        jButton6.setText("Cancelar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Creditos del Cliente"));

        jLabel1.setText("Compra");

        jLabel4.setText("Pagado");

        jLabel5.setText("Saldo");

        jLabel7.setText("Atraso Total");

        jLabel11.setText("Incremento Total");

        txtcompra.setEditable(false);

        txtpagado.setEditable(false);

        txtatrasototal.setEditable(false);

        txtsaldo.setEditable(false);

        txtincrementototal.setEditable(false);

        tablacreditos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tablacreditos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablacreditosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablacreditos);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, 0, 792, Short.MAX_VALUE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(txtcompra, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtpagado, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(txtsaldo, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtatrasototal, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel11)
                            .addComponent(txtincrementototal, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4)
                    .addComponent(jLabel7)
                    .addComponent(jLabel5)
                    .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtpagado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtatrasototal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtsaldo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtincrementototal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtcompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jButtonEliminarCredito1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/recycle_32.png"))); // NOI18N
        jButtonEliminarCredito1.setText("Eliminar último Pago");
        jButtonEliminarCredito1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEliminarCredito1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonEliminarCredito1)
                .addContainerGap(647, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonEliminarCredito1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jpanelpago, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpanelpago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton6)
                    .addComponent(jButtonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        if (txtcodigocliente.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Ingrese el codigo del cliente o presione el boton Ver listado de Clientes.", "ERROR", JOptionPane.ERROR_MESSAGE);
        } else {
            cargardatos();
            if (getclientevalido() == true) {
                jbvercreditos.setEnabled(true);
                cargartablacreditos();
            }
        }
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        ListadoClientes L = new ListadoClientes(idzona, this, true);
        L.setVisible(true);
        if (L.getidcliente().equals("")) {
            //return;
        } else {
            txtcodigocliente.setText(L.getidcliente());
            cargardatos();
            jbvercreditos.setEnabled(true);
            cargartablacreditos();
        }
    }//GEN-LAST:event_jButton8ActionPerformed

    private void jbvercreditosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbvercreditosActionPerformed
        CreditosClientesHistorial C = new CreditosClientesHistorial(this, true, id_cliente);
        C.setVisible(true);
        if (C.getidcredito() == 0) {
            //return;
        } else {
            txtcompra.setText(Float.toString(C.getcompra()));
            txtpagado.setText(Float.toString(C.getpagado()));
            txtsaldo.setText(Float.toString(C.getsaldo()));
            //cargardatos();
            //jbvercreditos.setEnabled(true);
        }
    }//GEN-LAST:event_jbvercreditosActionPerformed

    private void jButtonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAceptarActionPerformed
        if (txtcodigocliente.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Por favor seleccione un Cliente.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (txtpago.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Por favor ingrese el monto del Pago.", "Error", JOptionPane.ERROR_MESSAGE);
            txtpago.requestFocusInWindow();
            return;
        }
        if (txtincremento.getText().equals("")) {
            txtincremento.setText("0");
        }

        int res = JOptionPane.showConfirmDialog(null, "¿Desea guardar los datos del pago?", "Nuevo Pago", JOptionPane.YES_NO_OPTION);
        if (res == JOptionPane.YES_OPTION) {
            float pago = Float.parseFloat(txtpago.getText());
            String fecha_pago = (String) FORMATO_YYYY_MM_DD.format(jdfechapago.getDate());
            String fecha_carga_pago = (String) FORMATO_YYYY_MM_DD.format(new Date());
            float incremento = Float.parseFloat(txtincremento.getText());
            float incremento_total = Float.parseFloat(txtincrementototal.getText());
            float saldo = Float.parseFloat(txtsaldo.getText());
            float atraso = 0;
            float atraso_total = Integer.parseInt(txtatrasototal.getText());

            String id_usuario = idusuario;

            int fila = tablacreditos.getSelectedRow();
            int id_credito = Integer.parseInt(tablacreditos.getValueAt(fila, 0).toString());
            float pagado = Float.parseFloat(txtpagado.getText());

            float totalapagar = valor_cuota + atraso_total;     //Monto que debe pagar el Cliente en esta semana(Valor de la cuota + atraso total)
            atraso = totalapagar - pago;                        //Calculo del atraso. Si hay ATRASO quiere decir que el cliente pago menos de lo que debia en esa semana.
            if (atraso < 0) {
                atraso = 0;                                     //Si el atraso es menor que 0 entonces no hay atraso.
            }

            if (atraso > saldo) {                               // caso: al cliente le queda menos de una cuota en el saldo, entonces el atraso ya no se debe incrementar.
                atraso_total = saldo - pago;
                atraso = atraso_total;
            } else {
                atraso_total = atraso;                          //El atraso actual es el nuevo atraso_total
            }
            
            /*if (saldo <= valor_cuota){
                if(atraso > 0){                                 //caso: el saldo es menor a la cuota y el atraso acutal es mayor a 0, entonces se calcula... 
                    atraso_total = atraso_total - pago;
                }
                if (atraso_total < 0) {
                    atraso_total = 0;                           //Si el atraso es menor que 0 entonces no hay atraso.
                }
            }
            atraso = atraso_total;*/

            saldo = saldo - pago + incremento;                  //Calculo del Saldo. El incremento modifica el saldo.
            if(atraso > saldo && saldo <= valor_cuota){         //caso: si es la ultima cuota, el atraso debe tener como tope el saldo.
                atraso = saldo;
                atraso_total = saldo;
            }
            pagado = pagado + pago;                             //Calculo de lo que lleva Pagado el Cliente.
            compra_total = compra_total + incremento;           //El incremento modifica tambien la Compra Total del cliente.
            incremento_total = incremento_total + incremento;

            /*
             * Alta del PAGO
             */
            String consulta = "insert into pago (compra, pagado, saldo, pago, fecha, incremento, atraso, idcliente, idusuario, idcredito, fecha_carga_pago, liquidado) "
                    + "values('" + compra_total + "', '" + pagado + "', '" + saldo + "', '" + pago + "', '" + fecha_pago + "', '" + incremento + "', '" + atraso + "', '" + id_cliente + "', '" + id_usuario + "', '" + id_credito + "', '" + fecha_carga_pago + "', 'NO' )";
            try {
                Conectar();
                int done = stmt.executeUpdate(consulta);
                JOptionPane.showMessageDialog(null, "Se guardaron los datos del Pago.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
                db.close(stmt);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Error! No se pudo guardar los datos del pago", JOptionPane.ERROR_MESSAGE);
            }
            db.destroy();

            /*
             * Modificacion de la tabla Credito
             */
            String estado;
            if (pagado >= compra_total) {
                estado = "PAGADO";
                JOptionPane.showMessageDialog(null, "Se completo el pago del Credito.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
            } else {
                estado = "DEBE";
            }



            String consulta2 = "update credito "
                    + "set compra_total='" + compra_total + "', pagado='" + pagado + "', fecha_ultimo_pago='" + fecha_pago + "', saldo='" + saldo + "', atraso_total='" + atraso_total + "', incremento_total='" + incremento_total + "', estado='" + estado + "' "
                    + "where idcredito='" + id_credito + "'";

            try {
                Conectar();
                int done = stmt.executeUpdate(consulta2);
                //JOptionPane.showMessageDialog(null,"Se actualizaron los datos de la zona.","Aviso", JOptionPane.INFORMATION_MESSAGE);
                db.close(stmt);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Error! No se pudo actualizar los datos del Cliente.", JOptionPane.ERROR_MESSAGE);
            }
            db.destroy();
            limpiarcampos();
            txtcodigocliente.requestFocus();
            //this.dispose();
        }
    }//GEN-LAST:event_jButtonAceptarActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed

    private void tablacreditosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablacreditosMouseClicked
        int fila = tablacreditos.getSelectedRow();
        int id_credito = Integer.parseInt(tablacreditos.getValueAt(fila, 0).toString());

        String consulta = "SELECT compra,compra_total, pagado, saldo, atraso_total, incremento_total, cuota "
                + "FROM credito where idcredito = '" + id_credito + "'";

        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.beforeFirst();
            while (rs.next()) {
                txtcompra.setText(rs.getString("compra"));
                compra_total = Float.parseFloat(rs.getString("compra_total"));
                txtpagado.setText(rs.getString("pagado"));
                txtsaldo.setText(rs.getString("saldo"));
                txtatrasototal.setText(rs.getString("atraso_total"));
                txtincrementototal.setText(rs.getString("incremento_total"));
                valor_cuota = Float.parseFloat(rs.getString("cuota"));
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los datos del Credito.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        jpanelpago.setVisible(true);
        jdfechapago.requestFocusInWindow();
        //Para posicionar el cursor al principio de la fecha//
        JTextComponent jt = (JTextComponent) jdfechapago.getDateEditor();
        jt.setCaretPosition(0);
    }//GEN-LAST:event_tablacreditosMouseClicked

    private void txtcodigoclienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtcodigoclienteKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            jButton7.doClick();
        }
    }//GEN-LAST:event_txtcodigoclienteKeyPressed

    private void txtpagoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtpagoKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            txtincremento.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtpagoKeyPressed

    private void txtincrementoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtincrementoKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            //transfiere el foco si presionas enter
            jButtonAceptar.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtincrementoKeyPressed

    private void jButtonAceptarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButtonAceptarKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            jButtonAceptar.doClick();
        }
    }//GEN-LAST:event_jButtonAceptarKeyPressed

    private void jButtonEliminarCredito1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarCredito1ActionPerformed
        int fila = tablacreditos.getSelectedRow();
        String compra = tablacreditos.getValueAt(fila, 1).toString();
        String compra_total = tablacreditos.getValueAt(fila, 2).toString();
        String id_credito = tablacreditos.getValueAt(fila, 0).toString();
        String fecha_pago = "";
        String pago = "";
        String pagado = "";
        String incremento = "";
        String saldo = "";
        Float atraso_total = 0f;
        Float incremento_total = 0f;
        String id_pago = "";
        ResultSet rs;

        //TRAEMOS LOS DATOS DEL ULTIMO PAGO DEL CREDITO SELECCIONADO EN LA TABLA//
        String consulta = "SELECT * FROM pago WHERE idpago = (SELECT max(idpago) FROM pago WHERE idcredito ='" + id_credito + "' )";
        try {
            Conectar();
            rs = stmt.executeQuery(consulta);
            rs.beforeFirst();
            while (rs.next()) {
                fecha_pago = rs.getString("fecha");
                pago = rs.getString("pago");                //Se lo va a usar para restarlo al campo "pagado" del credito
                incremento = rs.getString("incremento");    //Se lo va a usar para restarlo al campo "compra_total" del credito
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los datos del ultimo pago.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        
        if(pago.equals("")){
            JOptionPane.showMessageDialog(null, "El credito seleccionado no registra pagos.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        int res = JOptionPane.showConfirmDialog(null, "¿Desea eliminar el ultimo pago del credito seleccionado? \n Compra:                 $ " + compra + " \n Compra total:        $ " + compra_total + " \n Fecha del pago:   " + fecha_pago + " \n Pago:                      $ " + pago + " \n Incremento:           $ " + incremento + " ", "Eliminar Pago", JOptionPane.YES_NO_OPTION);
        if (res == JOptionPane.YES_OPTION) {

            try {
                //TRAEMOS EL ULTIMO idpago DE LA TABLA PAGO//
                consulta = "SELECT max(idpago) as idpago FROM pago WHERE idcredito ='" + id_credito + "' ";
                rs = stmt.executeQuery(consulta);
                rs.beforeFirst();
                while (rs.next()) {
                    id_pago = rs.getString("idpago");
                }
                
                //TRAEMOS LOS DATOS DEL ULTIMO PAGO//
                consulta = "SELECT * FROM pago WHERE idpago = (SELECT max(idpago) FROM pago WHERE idcredito ='" + id_credito + "' )";
                rs = stmt.executeQuery(consulta);
                rs.beforeFirst();
                while (rs.next()) {
                    fecha_pago = rs.getString("fecha");
                    pagado = rs.getString("pagado");
                    saldo = rs.getString("saldo");
                }
                
                //ELIMINAMOS LOS DATOS DEL ULTIMO PAGO//
                consulta = "DELETE FROM pago WHERE idpago = '"+id_pago+"' ";
                stmt.executeUpdate(consulta);

                //TRAEMOS LOS DATOS DEL ULTIMO PAGO (el que antes era el penultimo pago)//
                //EN CASO DE QUE SOLO EXISTA UN PAGO, SE TOMARAN LOS DATOS QUE SE CONSULTARON ANTERIORMENTE (fecha_pago, pagado, saldo)//
                consulta = "SELECT * FROM pago WHERE idpago = (SELECT max(idpago) FROM pago WHERE idcredito ='" + id_credito + "' )";
                rs = stmt.executeQuery(consulta);
                rs.beforeFirst();
                while (rs.next()) {
                    fecha_pago = rs.getString("fecha");
                    //pagado = rs.getString("pagado");
                    saldo = rs.getString("saldo");
                }
                
                //VOLVEMOS A CALCULAR EL ATRASO Y EL INCREMENTO TOTAL//
                consulta = "SELECT * FROM pago WHERE idcredito ='" + id_credito + "' ";
                rs = stmt.executeQuery(consulta);
                rs.beforeFirst();
                while (rs.next()) {
                    atraso_total = atraso_total + rs.getFloat("atraso");
                    incremento_total = incremento_total + rs.getFloat("incremento");
                }

                //ACTUALIZAMOS LOS DATOS DEL CREDITO//
                consulta = "UPDATE credito SET compra_total=compra_total - " + incremento + ", pagado=pagado - " + pago + ", fecha_ultimo_pago='" + fecha_pago + "', estado='DEBE', saldo=saldo + '" + pago + "' - '" + incremento + "' , atraso_total='" + atraso_total + "', incremento_total='" + incremento_total + "' "
                        + "WHERE idcredito ='" + id_credito + "' ";
                stmt.executeUpdate(consulta);
                JOptionPane.showMessageDialog(null, "Se eliminaron todos los datos del ultimo Pago.", "Eliminar ultimo pago", JOptionPane.INFORMATION_MESSAGE);

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error al eliminar los datos del ultimo pago.\n "+ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
            }
            db.close(stmt);
            limpiarcampos();
            txtcodigocliente.requestFocus();
        }
    }//GEN-LAST:event_jButtonEliminarCredito1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Pagos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Pagos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Pagos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Pagos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        /*java.awt.EventQueue.invokeLater(new Runnable() {
        
        public void run() {
        Pagos dialog = new Pagos(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
        
        @Override
        public void windowClosing(java.awt.event.WindowEvent e) {
        System.exit(0);
        }
        });
        dialog.setVisible(true);
        }
        });*/
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButtonAceptar;
    private javax.swing.JButton jButtonEliminarCredito1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbvercreditos;
    private com.toedter.calendar.JDateChooser jdfechapago;
    private javax.swing.JPanel jpanelpago;
    private javax.swing.JTable tablacreditos;
    private javax.swing.JTextField txtatrasototal;
    private javax.swing.JTextField txtbarriocomercial;
    private javax.swing.JTextField txtbarrioparticular;
    private javax.swing.JTextField txtcodigocliente;
    private javax.swing.JTextField txtcompra;
    private javax.swing.JTextField txtdni;
    private javax.swing.JTextField txtdomiciliocomercial;
    private javax.swing.JTextField txtdomicilioparticular;
    private javax.swing.JTextField txtincremento;
    private javax.swing.JTextField txtincrementototal;
    private javax.swing.JTextField txtnombre;
    private javax.swing.JTextField txtpagado;
    private javax.swing.JTextField txtpago;
    private javax.swing.JTextField txtrubro;
    private javax.swing.JTextField txtsaldo;
    private javax.swing.JTextField txttelefono;
    // End of variables declaration//GEN-END:variables
    private conexion db;
    private Statement stmt;

    public void Conectar() {
        try {
            db = new conexion();      //instancia de la clase conexion.java
            db.init();
            Connection conn = db.getMyConnection();
            stmt = conn.createStatement();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Problemas al concetarse a la Base de Datos", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void cargardatos() {
        id_cliente = Integer.parseInt(txtcodigocliente.getText());
        String consulta = "Select dni,apellido,nombre,domicilio_particular,barrio_particular,domicilio_comercial,barrio_comercial,telefono,num_creditos,perno,r.descripcion"
                + " from cliente c, rubro r where idcliente = '" + id_cliente + "' and idzona = '" + idzona + "' and c.idrubro = r.idrubro";
        //int i = 0;
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.last();
            //System.out.println(rs.getRow());
            if (rs.getRow() == 0) {
                JOptionPane.showMessageDialog(null, "No existe ningun cliente con ese codigo. Por favor verifique el numero ingresado. ", "Error", JOptionPane.ERROR_MESSAGE);
                limpiarcampos();
            } else if (rs.getString("perno").equals("SI")) {
                JOptionPane.showMessageDialog(null, "El cliente seleccionado esta marcado como PERNO!. No se le puede asignar un credito. \nSi desea darle un credito debe modificar el campo PERNO en el menu Actualizaciones -> Clientes.", "Error", JOptionPane.ERROR_MESSAGE);
                limpiarcampos();
            } else {
                rs.beforeFirst();
                while (rs.next()) {
                    //txtidcliente.setText(rs.getString("idcliente"));
                    txtdni.setText(rs.getString("dni"));
                    txtnombre.setText(rs.getString("apellido") + ", " + rs.getString("nombre"));
                    txtdomicilioparticular.setText(rs.getString("domicilio_particular"));
                    txtbarrioparticular.setText(rs.getString("barrio_particular"));
                    txtdomiciliocomercial.setText(rs.getString("domicilio_comercial"));
                    txtbarriocomercial.setText(rs.getString("barrio_comercial"));
                    txttelefono.setText(rs.getString("telefono"));
                    txtrubro.setText(rs.getString("descripcion"));
                    //num_creditos = rs.getInt("num_creditos");
                }
                clientevalido = true;
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los datos del Cliente", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void limpiarcampos() {
        txtcodigocliente.setText("");
        txtdni.setText("");
        txtnombre.setText("");
        txtdomicilioparticular.setText("");
        txtbarrioparticular.setText("");
        txtdomiciliocomercial.setText("");
        txtbarriocomercial.setText("");
        txttelefono.setText("");
        txtrubro.setText("");
        txtcompra.setText("");
        txtpagado.setText("");
        txtsaldo.setText("");
        txtatrasototal.setText("");
        txtincrementototal.setText("");
        tablacreditos.setModel(new DefaultTableModel());
        jpanelpago.setVisible(false);
        clientevalido = false;
        txtpago.setText("");
        txtincremento.setText("");
    }

    private void cargartablacreditos() {
        boolean creditos = false;
        String consulta = "SELECT idcredito, compra as 'Compra', compra_total as 'Compra Total', plan as 'Plan', interes as 'Interes(%)',cuota as 'Cuota', "
                + "pagado as 'Pagado', fecha_compra as 'Fecha Compra', fecha_cancelacion as 'Cancelacion', fecha_ultimo_pago as 'Ultimo Pago', credito_numero as 'Num Credito', estado as 'Estado', "
                + "saldo as 'Saldo' "
                + "FROM credito where idcliente = '" + id_cliente + "' and estado = 'DEBE' "
                + "ORDER BY credito_numero DESC";
        /*fecha_ultimo_pago as 'Ultimo Pago'    ->   ERROR: no puede mostrar la fecha cuando es del tipo 0000-00-00*/
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.last();
            if (rs.getRow() > 0) {
                rs.beforeFirst();
                DefaultTableModel modelo = new DefaultTableModel();
                tablacreditos.setModel(modelo);
                ConversorRSaDefaultTableModel.completar(rs, modelo);
                //codigo para ocultar la primera columna (idplan)
                tablacreditos.getColumnModel().getColumn(0).setMaxWidth(0);
                tablacreditos.getColumnModel().getColumn(0).setMinWidth(0);
                tablacreditos.getColumnModel().getColumn(0).setPreferredWidth(0);
                tablacreditos.getColumnModel().getColumn(1).setPreferredWidth(30);
                tablacreditos.getColumnModel().getColumn(2).setPreferredWidth(40);
                tablacreditos.getColumnModel().getColumn(3).setPreferredWidth(20);
                tablacreditos.getColumnModel().getColumn(4).setPreferredWidth(40);
                tablacreditos.getColumnModel().getColumn(5).setPreferredWidth(30);
                tablacreditos.getColumnModel().getColumn(6).setPreferredWidth(30);
                tablacreditos.getColumnModel().getColumn(7).setPreferredWidth(50);
                tablacreditos.getColumnModel().getColumn(8).setPreferredWidth(50);
                tablacreditos.getColumnModel().getColumn(9).setPreferredWidth(50);
                tablacreditos.getColumnModel().getColumn(10).setPreferredWidth(30);
                tablacreditos.getColumnModel().getColumn(11).setPreferredWidth(30);
                tablacreditos.getColumnModel().getColumn(12).setPreferredWidth(40);
                tablacreditos.changeSelection(0, 0, false, true);
                creditos = true;
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar la tabla de Creditos de Clientes.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        if (creditos) {
            //tablacreditosMouseClicked(new MouseEvent(this, 0, 0, 0, 0, 0, 0, creditos));
            tablacreditosMouseClicked(null);
            jdfechapago.setDate(new Date());
            //txtpago.requestFocusInWindow();
            jdfechapago.requestFocusInWindow();
            //Para posicionar el cursor al principio de la fecha//
            JTextComponent jt = (JTextComponent) jdfechapago.getDateEditor();
            jt.setCaretPosition(0);
        }

    }
}